//
//  GiftViewController.m
//  beautyAccompany
//
//  Created by xiaocankeji on 15/11/11.
//  Copyright © 2015年 xiaocankeji. All rights reserved.
//

#import "GiftViewController.h"
#import "GiftTableViewCell.h"
static  NSInteger  giftCount = 20;
@interface GiftViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UIView *hintView;
@property (nonatomic, strong)UILabel *hintLabel;
@property (nonatomic, strong)UIImageView *hintImageView;
@property (nonatomic, strong)UILabel *priceLabel;
@property (nonatomic, strong)UILabel *giftHintLabel;
@property (nonatomic, strong)MPGift *gift;
@end

@implementation GiftViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    NSDictionary *userDic = [Utils getUserNicknameHeadurlObjectId:self.chatter];
    if (userDic == nil) {
        self.title = @"送礼物";
        AVQuery *userQUery = [MPUser query];
        [userQUery whereKey:@"objectId" equalTo:self.chatter];
        [userQUery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            if (!error) {
                MPUser *qUser = (MPUser *)object;
                [Utils saveChatUserDataNicknameUser:qUser];
                self.title = [NSString stringWithFormat:@"送%@小礼物",qUser.nickname];
            }
        }];
    }else{
        
        NSString *nickname = [userDic objectForKey:@"nickname"];
        self.title = [NSString stringWithFormat:@"送%@小礼物",nickname];
    }
    [AVAnalytics event:@"打开礼物店铺"];
   // self.showRefreshFooter = YES;//设置为yes的时候会出现点击加载更多
    self.showRefreshHeader = YES;
    self.showTableBlankView = YES;
     [self requestDataIsHeader:YES];
    // Do any additional setup after loading the view.
}
- (void)requestDataIsHeader:(BOOL)is
{
    [HUD setOnViewWithTitle:@"请求中" animated:YES];
    AVQuery *query = [MPGift query];
    [query whereKey:@"status" equalTo:[NSNumber numberWithInteger:1]];
    [query orderByAscending:@"priority"];
    query.limit = giftCount;
    query.skip = self.page * giftCount;
    query.cachePolicy = kAVCachePolicyNetworkElseCache;
    query.maxCacheAge = 7200;
    [query includeKey:@"img"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
       
        if (error) {
            [HUD Prompt:@"网络错误"];
        }else{
            //请求结束后根据结果决定是否展示
            
            if (self.page == 0) {
                [self.dataArray removeAllObjects];
            }
            self.page ++;
            [self.dataArray addObjectsFromArray:objects];
            [self.tableView reloadData];
        }
        
        if (self.dataArray.count == 0   ) {
            [self viewControllerPrompt:CGRectMake(0, 84 , DeviceWidth, DeviceHeight-84) Text:@"没有找到礼物,下拉刷新试试" Image:[UIImage imageNamed:@"lianren_nul"]];
        }else{
           
            if (self.showRefreshFooter == NO) {
                self.showRefreshFooter = YES;
            }
        }
        
        
        [self tableViewDidFinishTriggerHeader:is reload:YES];
        [HUD hideFromViewAnimated:YES];
    }];
}
/**
 *  下拉刷新事件
 */
- (void)tableViewDidTriggerHeaderRefresh
{
    self.page = 0;
    
    [self requestDataIsHeader:YES];
  
}

/**
 *  上拉加载事件
 */
- (void)tableViewDidTriggerFooterRefresh
{
    [self requestDataIsHeader:NO];
   
}
//- (NSArray *)giftArr
//{
//    if (_giftArr == nil) {
//        _giftArr = [NSArray array];
//    }
//    return _giftArr;
//}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, 84)];
    headerView.backgroundColor = [UIColor clearColor];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, 84)];
    imageView.image = [UIImage imageNamed:@"giftShop"];
    imageView.backgroundColor = [UIColor blackColor];
    [headerView addSubview:imageView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(DeviceWidth/2-50, 47, 100, 24)];
    label.text = @"礼物店铺";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    [headerView addSubview:label];
    
    UIView *leftLine = [[UIView alloc] initWithFrame:CGRectMake(0, 34+50/2-0.5, DeviceWidth/2-50, 1)];
    leftLine.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:leftLine];
    
    UIView *rightLine = [[UIView alloc] initWithFrame:CGRectMake(DeviceWidth/2+50, 34+50/2-0.5, DeviceWidth/2-50, 1)];
    rightLine.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:rightLine];
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 84;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndentifier = @"giftCell";
    GiftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell = [[GiftTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        
    }
    if ([self.dataArray count]) {
        MPGift *gift = self.dataArray[indexPath.row];
        [cell.giftAvatarImg sd_setImageWithURL:[NSURL URLWithString:gift.img.url] placeholderImage:[UIImage imageNamed:@"chat_gift_icon"]];
        cell.giftNameLabel.text = gift.name;
        cell.giftSignatureLabel.text = gift.info;
        cell.priceLabel.text = [NSString stringWithFormat:@"%.0f时光",gift.price];
    }
    return cell;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return 1;
}

//cell数目
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 84;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MPGift *gift = self.dataArray[indexPath.row];
    [self hintViewGift:gift];
    
}
- (void)clickHintView
{
    if (_hintView.alpha == 1) {
        [Utils Hidden:_hintView Bool:NO];
    }else{
        [Utils Hidden:_hintView Bool:YES];
    }
}
- (void)hintViewGift:(MPGift *)gift
{
    [self hintView];
    [self clickHintView];
    self.gift = gift;
    _hintLabel.text = gift.name;
    [_hintImageView sd_setImageWithURL:[NSURL URLWithString:gift.img.url] placeholderImage:[UIImage imageNamed:@"chat_gift_icon"]];
    _priceLabel.text = [NSString stringWithFormat:@"%.0f时光",gift.price];
    _giftHintLabel.text = gift.info;
}
- (UIView *)hintView
{
    if (!_hintView) {
        _hintView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)];
        _hintView.backgroundColor = RGBA(1, 1, 1, 0.3);
        
        [[UIApplication sharedApplication].delegate.window addSubview:_hintView];
        _hintView.alpha = 0;
        UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickHintView)];
        [_hintView addGestureRecognizer:tapGR];
        
        UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(DeviceWidth/2-127.5, DeviceHeight/2-127.5, 255, 255)];
        whiteView.backgroundColor = [UIColor whiteColor];
        whiteView.layer.masksToBounds = YES;
        whiteView.layer.cornerRadius = 5;
        [_hintView addSubview:whiteView];
        
        self.hintLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, whiteView.frame.size.width, 20)];
        self.hintLabel.textColor = RGBA(14, 16, 18, 1);
        self.hintLabel.textAlignment = NSTextAlignmentCenter;
        [whiteView addSubview:_hintLabel];
        
        self.hintImageView = [[UIImageView alloc] initWithFrame:CGRectMake(whiteView.frame.size.width/2-60, 35, 120, 120)];
        [whiteView addSubview:self.hintImageView];
        
        self.priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 155 , whiteView.frame.size.width, 20)];
        _priceLabel.textColor = APPCOLOR(1);
        _priceLabel.font = kFont(15);
        _priceLabel.textAlignment = NSTextAlignmentCenter;
        [whiteView addSubview:_priceLabel];
        
        self.giftHintLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 175, whiteView.frame.size.width-30, 30)];
        self.giftHintLabel.numberOfLines = 0;
        self.giftHintLabel.textColor = [UIColor darkGrayColor];
        self.giftHintLabel.font = kFont(13);
        self.giftHintLabel.textAlignment = NSTextAlignmentCenter;
        [whiteView addSubview:self.giftHintLabel];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, whiteView.frame.size.height - 45, whiteView.frame.size.width, 0.5)];
        line.backgroundColor = RGBA(1, 1, 1, 0.1);
        [whiteView addSubview:line];
        UIView *otherLine = [[UIView alloc] initWithFrame:CGRectMake(whiteView.frame.size.width/2.0-0.25, whiteView.frame.size.height - 45, 0.5, 45)];
        otherLine.backgroundColor = RGBA(1, 1, 1, 0.1);
        [whiteView addSubview:otherLine];
        
        UIButton *leftbt = [UIButton buttonWithType:UIButtonTypeCustom];
        leftbt.frame = CGRectMake(0, whiteView.frame.size.height - 46, whiteView.frame.size.width/2, 44);
        [leftbt setTitle:@"取消" forState:UIControlStateNormal];
        [leftbt setTitleColor:APPCOLOR(1) forState:UIControlStateNormal];
        leftbt.titleLabel.font = kFont(15);
        [leftbt addTarget:self action:@selector(clickHintView) forControlEvents:UIControlEventTouchUpInside];
        [whiteView addSubview:leftbt];
        
        UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
        bt.frame = CGRectMake(whiteView.frame.size.width/2, whiteView.frame.size.height - 46, whiteView.frame.size.width/2, 44);
        [bt setTitle:@"赠送" forState:UIControlStateNormal];
        [bt setTitleColor:APPCOLOR(1) forState:UIControlStateNormal];
        bt.titleLabel.font = kFont(15);
        [bt addTarget:self action:@selector(give) forControlEvents:UIControlEventTouchUpInside];
        [whiteView addSubview:bt];
    }
    return _hintView;
}


//赠送
- (void)give
{
    NSDictionary *ext = @{@"giftType": @EMMESSAGE_EXT_TYPE_GIFT_MSG,@"giftImg":self.gift.img.url,@"giftName":self.gift.name,@"giftInfo":self.gift.info};
    NSString *text = [NSString stringWithFormat:@"送你一个礼物“%@”",self.gift.name];
    [self interpositionMessageText:text andUserObjectId:self.chatter from:self.chatter dic:ext];
    [Utils Hidden:_hintView Bool:NO];
    
//    MPUser *user = [MPUser currentUser];
//    NSDictionary *params = @{@"userId":user.objectId,@"price":[NSNumber numberWithFloat:-self.gift.price/10.0],@"type":[NSNumber numberWithInteger:INCOME_TYPE_SENDGIFT],@"aboutUserId":self.chatter};
//    [HUD setOnViewWithTitle:@"加载中" animated:YES];
//    [AVCloud callFunctionInBackground:@"modifyBalance"withParameters:params block:^(id object, NSError *error) {
//        
//        if (error) {
//            //是吧
//            [HUD hideFromViewAnimated:YES];
//            if([error code] == 201){
//                [HUD Prompt:@"余额不足"];
//            }else{
//                [HUD Prompt:@"网络错误"];
//            }
//            [Utils Hidden:_hintView Bool:NO];
//        }else{
//            //成功
//            [HUD hideFromViewAnimated:YES];
//            NSDictionary *taParams = @{@"userId":self.chatter,@"price":[NSNumber numberWithFloat:self.gift.price*0.7/10.0],@"type":[NSNumber numberWithInteger:INCOME_TYPE_BESENDGIFT],@"aboutUserId":user.objectId};
//            [self modifyBalance:taParams];
//            
//            NSDictionary *ext = @{@"giftType": @EMMESSAGE_EXT_TYPE_GIFT_MSG,@"giftImg":self.gift.img.url,@"giftName":self.gift.name,@"giftInfo":self.gift.info};
//            NSString *text = [NSString stringWithFormat:@"送你一个礼物“%@”",self.gift.name];
//            NSString *mlsystemText = [NSString stringWithFormat:@"%@送给你了“%@”,已兑换成%.0f时光,存进你的钱包",user.nickname,self.gift.name,self.gift.price*0.7];
//            // [self interpositionMessageText:mlsystemText andUserObjectId:self.objectId from:@"mlsystem" dic:[NSDictionary dictionary]];
//            NSDictionary *params2 = @{@"touserId": self.chatter,@"msg":mlsystemText};
//            [AVCloud callFunctionInBackground:@"sendSysMsg" withParameters:params2 block:^(id object, NSError *error) {
//            }];
//            MPGiftRecord *giftRecord = [MPGiftRecord object];
//            giftRecord.user = user;
//            MPUser *chatUser = [MPUser object];
//            chatUser.objectId = self.chatter;
//            giftRecord.receiver = chatUser;
//            giftRecord.gift = self.gift;
//            [giftRecord saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//                
//            }];
//            
//            [self interpositionMessageText:text andUserObjectId:self.chatter from:user.objectId dic:ext];
//            [Utils Hidden:_hintView Bool:NO];
//            [HUD Prompt:@"礼物赠送成功"];
//            
//        }
//        
//        
//    }];
}
-(void)modifyBalance:(NSDictionary*)params
{
    [AVCloud callFunctionInBackground:@"modifyBalance" withParameters:params block:^(id object, NSError *error) {
        if (error) {
        }
    }];
}
- (void)interpositionMessageText:(NSString *)text andUserObjectId:(NSString *)objectId from:(NSString *)from dic:(NSDictionary *)ext
{
    EMChatText *txt = [[EMChatText alloc] initWithText:text];
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:txt];
    EMMessage *message = [[EMMessage alloc] initWithReceiver:objectId bodies:@[body]];
    message.from = from;
    message.ext = ext;
    message.messageType = eMessageTypeChat; // 设置为单聊消息
    EMMessage *newMessage =  [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil];
    NSDictionary *dic=@{@"message":newMessage ,@"objectId":objectId};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"addHintMessage" object:self userInfo:dic];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
